package com.felix.webmagic.processor;

import com.felix.webmagic.pojo.Blog;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;

/**
 * @author code4crafter@gmail.com <br>
 */
public class SinaBlogProcessor implements PageProcessor {

    private List<Blog> list;

    public SinaBlogProcessor(List<Blog> list) {
        this.list = list;
    }

    public static final String URL_LIST = "http://blog\\.sina\\.com\\.cn/s/articlelist_1487828712_0_\\d+\\.html";

    public static final String URL_POST = "http://blog\\.sina\\.com\\.cn/s/blog_\\w+\\.html";

    private Site site = Site
            .me()
            .setDomain("blog.sina.com.cn")
            .setSleepTime(3000)
            .setUserAgent(
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");

    @Override
    public void process(Page page) {
        Blog blog = new Blog();
        //列表页
        if (page.getUrl().regex(URL_LIST).match()) {
            page.addTargetRequests(page.getHtml().xpath("//div[@class=\"articleList\"]").links().regex(URL_POST).all());
            page.addTargetRequests(page.getHtml().links().regex(URL_LIST).all());
            //文章页
        } else {
            blog.setTitle(page.getHtml().xpath("//div[@class='articalTitle']//h2[@class='titName SG_txta']").regex("\\>(.*)\\<")
                    .toString());
            blog.setContent(page.getHtml().xpath("//div[@id='articlebody']//div[@class='articalContent']").toString());
            blog.setData(page.getHtml().xpath("//div[@id='articlebody']//span[@class='time SG_txtc']").regex("\\((.*)\\)").toString());
            if (blog.getTitle() == null) {
                //skip this page
                page.setSkip(true);
            } else {
                list.add(blog);
            }
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

}